package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> level1menu = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    categoryEntity.setChildrens(getChildrenS(categoryEntity, categoryEntities));
                    return categoryEntity;
                }).sorted((CategoryEntity1, CategoryEntity2) -> (CategoryEntity1.getSort()==null?0:CategoryEntity1.getSort()) -(CategoryEntity2.getSort()==null?0:CategoryEntity2.getSort()))
                .collect(Collectors.toList());
        return level1menu;
    }

    @Override
    public void removeMenuByIds(List<Long> list) {
        //TODO 1.检查当前菜单有无被引用，才能删除
        baseMapper.deleteBatchIds(list);
    }

    @Override
    public Long[] findCatelogPath(Long attrGroupId) {
        List<Long> path = new ArrayList<>();
        findPath(attrGroupId, path);
        Collections.reverse(path);
        return  path.toArray(new Long[0]);
    }
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        //同步更新其他 所有 有关联的表
        if (!StringUtils.isEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
            //TODO 更新其他关联表
        }
    }

    public void findPath(Long id, List<Long> path) {
        path.add(id);
        CategoryEntity categoryEntity = baseMapper.selectById(id);
        if (categoryEntity.getParentCid()!=0){
            findPath(categoryEntity.getParentCid(),path);
        }
    }

    public List<CategoryEntity> getChildrenS(CategoryEntity root,List<CategoryEntity> all){
        //== 比较：在 Long 类型的包装对象中，== 比较的是对象引用，所以只有在 Long 的值位于 -128 到 127 范围内时，== 才会返回 true，因为这些值会被缓存。
        // 超出这个范围的 Long 值会被装箱成新的对象，导致引用不同，从而 == 比较返回 false。
        List<CategoryEntity> collect = all.stream().filter(categoryEntity -> Objects.equals(categoryEntity.getParentCid(), root.getCatId()))
                .map(categoryEntity -> {
                    //递归找孩子
                    categoryEntity.setChildrens(getChildrenS(categoryEntity, all));
                    return categoryEntity;
                }).sorted( (CategoryEntity1,CategoryEntity2)->(CategoryEntity1.getSort()==null?0:CategoryEntity1.getSort()) -(CategoryEntity2.getSort()==null?0:CategoryEntity2.getSort()))
                .collect(Collectors.toList());
        return collect;
    }
}